﻿using LJLNet.SocketTCPPeer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LJLCommon.Helper;
using System.Threading.Tasks;

namespace LJLNet.Thread
{
    public class ReceiveThread : BaseThread
    {
        private BasePeer mPeer;

        public ReceiveThread(BasePeer peer)
        {
            mPeer = peer;
        }

        //运行的内容
        protected override void Run()
        {
            if (mPeer.mSocket != null)
            {
                while (true)
                {
                    try
                    {
                        //从客户端接收消息
                        byte[] buffer = new byte[1024];//设置一个消息接收缓冲区  
                        mPeer.mSocket.Receive(buffer);//该状态处于一个暂停状态，知道接收到消息，并返回字节数  

                        Dictionary<byte, object> parameters = DictToPackageHelper.DeSerializa(ASCIIEncoding.UTF8.GetString(buffer));
                        mPeer.OnOperationRequest(parameters);                       
                    }
                    catch
                    {
                        Console.WriteLine("一个客户端断开连接");
                        //断开线程
                        this.Stop();
                        //将该客户端移除
                        mPeer.OnDisconnect();
                        ServerMgr.GetInstance.peerList.Remove(mPeer);
                        mPeer = null;
                    }
                }
            }
        }
    }
}
